package com.cloud.utils;

import cn.hutool.core.convert.Convert;
import com.cloud.common.configure.TransmittableHolder;
import com.cloud.common.constants.GlobalConstants;
import com.cloud.domain.LoginUser;
import com.cloud.exception.CustomException;
import com.cloud.exception.LoginException;
import jakarta.servlet.http.HttpServletRequest;

/**
 * Security 权限工具
 *
 * @author yzj
 */
public class SecurityUtils {

    // 获取用户ID
    public static Long getUserId() {
        Long userId = TransmittableHolder.getUserId();
        if (StringUtils.isNull(userId)) {
            HttpServletRequest request = ServletUtils.getRequest();
            userId = Convert.toLong(request.getHeader(GlobalConstants.userId));
        }
        return userId;
    }

    // 获取账户名称
    public static String getUserName() {
        String userName = TransmittableHolder.getUserName();
        if (StringUtils.isEmpty(userName)) {
            HttpServletRequest request = ServletUtils.getRequest();
            userName = request.getHeader(GlobalConstants.userName);
        }
        return userName;
    }

    // 获取当前用户部门ID
    public static Long getDeptId() {
        Long deptId = TransmittableHolder.getDeptId();
        if (StringUtils.isNull(deptId)) {
            HttpServletRequest request = ServletUtils.getRequest();
            deptId = Convert.toLong(request.getHeader(GlobalConstants.deptId));
        }
        return deptId;
    }

    // 获取登录用户信息
    public static LoginUser getLoginUser() {
        return TransmittableHolder.getLoginUser();
    }

    // 获取系统编号
    public static String getSysCode() {
        HttpServletRequest request = ServletUtils.getRequest();
        String tokenHeader = request.getHeader(GlobalConstants.appTokenHeader);
        if (StringUtils.isEmpty(tokenHeader)) {
            throw new CustomException(LoginException.TOKEN_IS_EMPTY.getCode(),
                    LoginException.TOKEN_IS_EMPTY.getMsg());
        }
        return tokenHeader;
    }

    // 获取请求token信息
    public static String getToken() {
        HttpServletRequest request = ServletUtils.getRequest();
        String tokenHeader = request.getHeader(GlobalConstants.tokenHeader);
        if (StringUtils.isNotEmpty(tokenHeader)) {
            throw new CustomException(LoginException.TOKEN_IS_EMPTY.getCode(),
                    LoginException.TOKEN_IS_EMPTY.getMsg());
        }
        return tokenHeader;
    }

}
